import { Model } from 'dva';
import moment from 'moment';
import BookService from '../../services/system/books';
import { BookDto } from '../../pages/System/Account/types/book.dto';
import { ReduxAction } from '../global';

export interface BooksState {
  bookList: BookDto[];
}

const model: Model = {
  namespace: 'books',
  state: {
    bookList: [],
  },
  subscriptions: {},
  reducers: {
    setState(state, action: ReduxAction) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  effects: {
    *bookList(action, { put, call }) {
      const res = yield call(BookService.bookList, action.payload);
      // debugger;
      // Array.isArray(res.data) &&
      res.data.forEach(v => {
        v.createdAt = moment(v.createdAt).format('YYYY-MM-DD');
      });
      yield put({ type: 'setState', payload: { bookList: res.data || [] } });
    },

    *addBook(action, { call }) {
      return yield call(BookService.addBook, action.payload);
    },

    *editBook(action, { call }) {
      return yield call(BookService.modifyBookById, action.payload);
    },

    *delBook(action, { call }) {
      return yield call(BookService.deleteBookById, action.payload);
    },
  },
};
export default model;
